package cn.tedu.order.tcc;

import cn.tedu.order.entity.Order;
import cn.tedu.order.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class OrderTccActionImpl implements OrderTccAction{
    @Autowired
    private OrderMapper orderMapper;




    @Transactional
    @Override
    public boolean prepare(BusinessActionContext ctx,
                           Long id,
                           Long userId,
                           Long productId,
                           Integer count,
                           BigDecimal money) {
        //状态0，表示冻结状态
        orderMapper.create(new Order(id,userId,productId,count,money,0));
        //保存一个标记，表示1阶段完成
        ResultHolder.setResult(ResultHolder.class, ctx.getXid(), "p");

        return true;
    }




    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        //如果没有标记，后面不执行
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid())== null){
            return true;
        }
        /**
         * ctx对象 从第一阶段向第二阶段传递时，是先转成json，在送json转回上下文对象，
         * 其中保存的数据可能丢失数据类型
         */
        //  1 表示正常状态
        Long orderId = Long.valueOf(ctx.getActionContext("id").toString());
        orderMapper.updateStatus(orderId, 1);

        //提交完成，删除标记
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }




    @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
        //幂等性控制，防止重复提交，重复回滚
        if (ResultHolder.getResult(OrderTccAction.class, ctx.getXid())== null){
            return true;
        }
        Long orderId = Long.valueOf(ctx.getActionContext("id").toString());
        orderMapper.deleteById(orderId);
        //提交完成，删除标记
        ResultHolder.removeResult(OrderTccAction.class, ctx.getXid());
        return true;
    }
}
